//
//  ViewController.m
//  3.22、线程安全
//
//  Created by 李坤 on 16/12/14.
//
//

/*
 模拟多个线程并发修改一个变量
 */
#import "ViewController.h"

@interface ViewController ()
//剩余票数
@property(nonatomic,assign)int leftTicketsCount;

@property(nonatomic,strong)NSThread *t1;

@property(nonatomic,strong)NSThread *t2;

@property(nonatomic,strong)NSThread *t3;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //默认有20张票
    self.leftTicketsCount = 20;
    //开启多个线程，模拟售票员售票
    self.t1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
    self.t1.name = @"售票员1";
    
    self.t2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
    self.t2.name = @"售票员2";
    
    self.t3 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
    self.t3.name = @"售票员3";
}

- (void)sellTickets{
    while (1) {
        @synchronized (self) {
            //1.先检查票数
            int count = self.leftTicketsCount;
            if(count>0){
                //暂停一段时间
                [NSThread sleepForTimeInterval:0.002];
                //2.票数-1
                self.leftTicketsCount = count - 1;
                
                //获取当前线程
                NSThread *current = [NSThread currentThread];
                NSLog(@"%@--卖了一张票，剩余%d张票",current,self.leftTicketsCount);
            }else{
                //退出线程
                NSLog(@"%@退出了",[NSThread currentThread]);
                [NSThread exit];
            }
        }
    }
}

static bool flag = YES;
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //开启线程
    if(flag){
        [self.t1 start];
        [self.t2 start];
        [self.t3 start];
        flag = NO;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
